package com.bamanker.sms_service.controller;

import com.bamanker.sms_service.service.MyMailService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author bamanker
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class SmsController {

    private static ConcurrentHashMap<String, Long> requestCountMap = new ConcurrentHashMap<>();

    private final MyMailService myMailService;

    public SmsController(MyMailService myMailService) {
        this.myMailService = myMailService;
    }

    @RequestMapping("/smsRec")
    public String smsReceiver(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("code") String code) {
        if (!limitRequestFrequency(request)) {
            response.setStatus(429);
            return "Too many requests";
        } else {
            if (null != code) {

                log.info("收到消息，参数为：{}", code);
                String sub = "最新的验证码";
                myMailService.sendMail(sub, code);
                return "OK";
            }
        }
        return "FAIL";
    }

    @RequestMapping("/test")
    public String testApi(HttpServletRequest request, HttpServletResponse response, @RequestParam("code") String code) {
        if (!limitRequestFrequency(request)) {
            response.setStatus(429);
            return "Too many requests";
        } else {
            if (null != code) {
                log.info("收到消息，参数为：{}", code);
                String sub = "最新的验证码";
                return "OK";
            }
        }
        return "FAIL";
    }

    private boolean limitRequestFrequency(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();
        String key = ip + ":" + uri;
        log.info("this request:{}",key);
        Long lastRequestTime = requestCountMap.get(key);
        long now = System.currentTimeMillis();
        if (lastRequestTime != null && (now - lastRequestTime) < 5000) {
            return false;
        }
        requestCountMap.put(key, now);
        return true;
    }
}
